/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.material.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.common.annotation.ServiceLog;
import org.springblade.common.constant.TrainingOperateConstant;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.redis.lock.RedisLock;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.classes.bo.UserBindingBo;
import org.springblade.modules.classes.service.IUserBindingService;
import org.springblade.modules.course.entity.CourseEntity;
import org.springblade.modules.library.entity.MaterialLibraryEntity;
import org.springblade.modules.library.service.IAllowUserService;
import org.springblade.modules.library.service.IMaterialLibraryService;
import org.springblade.modules.library.vo.AllowUserVO;
import org.springblade.modules.personal.entity.UserBaseEntity;
import org.springblade.modules.personal.service.IUserBaseService;
import org.springblade.modules.resource.enums.AttachType;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.material.entity.CoursewareEntity;
import org.springblade.modules.material.vo.CoursewareVO;
import org.springblade.modules.material.wrapper.CoursewareWrapper;
import org.springblade.modules.material.service.ICoursewareService;
import org.springblade.core.boot.ctrl.BladeController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

/**
 * 学习资料 控制器
 *
 * @author
 * @since 2023-03-22
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-courseware/courseware")
@Api(value = "学习资料", tags = "学习资料接口")
public class CoursewareController extends BladeController {

	private final ICoursewareService coursewareService;
	private final CommonUtil commonUtil;
	private final IUserBindingService userBindingService;
	private final IAllowUserService allowUserService;
	private final IUserBaseService userBaseService;
	private final IMaterialLibraryService materialLibraryService;

	/**
	 * 学习资料 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入courseware")
	public R<CoursewareVO> detail(CoursewareEntity courseware) {
		CoursewareEntity detail = coursewareService.getOne(Condition.getQueryWrapper(courseware));
		return R.data(CoursewareWrapper.build().entityVO(detail));
	}
	/**
	 * 学习资料 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入courseware")
	public R<IPage<CoursewareVO>> list(CoursewareEntity courseware, Query query) {
//		if (!commonUtil.checkRoleAlias(TrainingRoleConstant.Administrator)) courseware.setCreateUser(AuthUtil.getUserId());
		commonUtil.checkRoleAliasPermission(courseware,courseware.getClass());
		IPage<CoursewareEntity> pages = coursewareService.page(Condition.getPage(query), Condition.getQueryWrapper(courseware).orderByAsc("sort"));
		return R.data(CoursewareWrapper.build().pageVO(pages));
	}

	/**
	 * 学习资料 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入courseware")
	public R<IPage<CoursewareVO>> page(CoursewareVO courseware, Query query) {
		IPage<CoursewareVO> pages = coursewareService.selectCoursewarePage(Condition.getPage(query), courseware);
		return R.data(pages);
	}

	/**
	 * 学习资料 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入courseware")
	@ServiceLog(value = TrainingOperateConstant.LIBRARY,operate = TrainingOperateConstant.ADD,describe ="新增学习资料" )
	@Transactional(rollbackFor = Exception.class)
	public R save(@Valid @RequestBody CoursewareEntity courseware) {
		courseware.setDownloadNum(0);
		selectByLinkAndUpdateLinkName(courseware.getUrl(),courseware.getCoursewareName(),AttachType.DATA_SHARE.getCategory());
		return R.status(coursewareService.save(courseware));
	}

	/**
	 * 一键新增小节资源 ，选择上传资源时，该资源链接没有名称，需要赋上
	 */
	public void selectByLinkAndUpdateLinkName(String link,String linkName,int attachType){
		MaterialLibraryEntity materialLibraryEntity = materialLibraryService.getOne(Wrappers.<MaterialLibraryEntity>query()
			.lambda().eq(MaterialLibraryEntity::getStoragePath, link));
		if (null!=materialLibraryEntity ){
			if (StringUtils.isNotEmpty(linkName))materialLibraryEntity.setMeterialName(linkName);
			materialLibraryEntity.setStatus(2);
			materialLibraryEntity.setCategory(attachType);
			materialLibraryService.updateById(materialLibraryEntity);
		}
	}

	/**
	 * 学习资料 修改
	 */
	@RedisLock(value = "lock:course:courseware")
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入courseware")
	public R update(@Valid @RequestBody CoursewareEntity courseware) {
		return R.status(coursewareService.updateById(courseware));
	}


	/**
	 * 学习资料 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(coursewareService.deleteLogic(Func.toLongList(ids)));
	}



	/**
	 * 学习资料 添加下载数量
	 */
	@GetMapping("/download/Callback")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "下载接口", notes = "传入courseware")
	@RedisLock(value = "lock:course:courseware")
	public R<String> addDownloadNum(String  coursewareId) {
		coursewareService.addDownloadNum(coursewareId);
		return R.data(coursewareService.getById(coursewareId).getUrl());
	}


	/**
	 * 学习资料 添加下载数量
	 */
	@GetMapping("/select")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "下拉接口", notes = "传入courseware")
	public R select(@ApiIgnore @RequestParam Map<String, Object> entity) {
		QueryWrapper<CoursewareEntity> queryWrapper = Condition.getQueryWrapper(entity, CoursewareEntity.class);
		return R.data(coursewareService.list(queryWrapper));
	}


	/**
	 * 资料分享可被允许的用户
	 */
	@PostMapping("/allow-users-save")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "添加允许查看资料的用户", notes = "")
	@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
	public R save(@Valid @RequestBody UserBindingBo bo) {
		userBindingService.addUserBinding(bo);
		return R.success("保存成功");
	}

	/**
	 * 资料分享用户列表分页
	 */
	@GetMapping("/allow-users-list")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "资料分享用户列表分页", notes = "")
	public R allowUsersPage(AllowUserVO allowUserVO, Query query) {
		IPage<AllowUserVO> allowUserVOIPage = allowUserService.selectAllowUserPage(Condition.getPage(query), allowUserVO);
//		allowUserVOIPage.getRecords().forEach(page->{
//			CoursewareEntity coursewareEntity = coursewareService.getById(page.getDataShareId());
//			if (null!=coursewareEntity)page.setCoursewarName(coursewareEntity.getCoursewareName());
//			UserBaseEntity userBaseEntity = userBaseService.selectByUserId(page.getAllowUserId());
//			if (null!=userBaseEntity){
//				page.setIdCard(userBaseEntity.getIdCard());
//				page.setUserName(userBaseEntity.getUserName());
//			}
//		});
		return R.data(allowUserVOIPage);
	}


	/**
	 * 学习资料 删除
	 */
	@PostMapping("/allow-users-remove")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R removeAllowUser(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(allowUserService.deleteLogic(Func.toLongList(ids)));
	}



}
